import { useRef } from "react";
import { useMount } from "react-use";

const TestImageData: React.FC = () => {
  const canvas = useRef<HTMLCanvasElement>(null);

  useMount(() => {
    putImageData();
    colorSpace();
    getImageData();
  });

  //把imagedata渲染到canvas中
  const putImageData = () => {
    const ctx = canvas.current?.getContext("2d")!;
    const [width, height] = [200, 100];
    const imageData = new ImageData(width, height);
    /**
     * ImageData.prototype.data: Uint8ClampedArray
     * 八位无符号整型数组，一个位置占一个字节
     * 每个位置所存储十进制范围为0 ~ 255
     *
     * length = width * height * 4
     * 每四个位置表示一个像素点，存储R G B A 的值
     *
     */
    for (let i = 0; i < width * height; i++) {
      // R  G  B  A   0 ~ 255
      // 红 绿 蓝 色彩空间/透明度
      const index = i * 4;
      const [R, G, B, A] = [255, 0, 0, 255];
      imageData.data[index + 0] = R;
      imageData.data[index + 1] = G;
      imageData.data[index + 2] = B;
      imageData.data[index + 3] = A;
    }
    // console.log(imageData);
    ctx.putImageData(imageData, 0, 0);
  };

  const colorSpace = () => {
    var ctx = canvas.current?.getContext("2d")!;
    var grd = ctx.createLinearGradient(0, 200, 256, 100);
    grd.addColorStop(0, "rgb(0,0,255)");
    grd.addColorStop(0.25, "rgb(0,255,0)");
    grd.addColorStop(0.5, "rgb(255,255,0)");
    grd.addColorStop(0.75, "rgb(255,0,0)");
    ctx.fillStyle = grd;
    ctx.fillRect(0, 200, 256, 100);
    ctx.rect(0, 200, 256, 100);
    const data = ctx.getImageData(0, 200, 256, 100);
    console.log(data);
  };

  //在画布上画一张图片，然后获取像素点数据
  const getImageData = () => {
    const ctx = canvas.current?.getContext("2d")!;
    const img = new Image();
    img.src = "/vite.svg";
    img.onload = () => {
      const { naturalWidth, naturalHeight } = img;
      ctx!.drawImage(img, 0, 0, naturalWidth, naturalHeight);
      const data = ctx.getImageData(0, 0, naturalWidth, naturalHeight);
      console.log(data);
    };
  };

  return <canvas ref={canvas} width={400} height={400} className="border" />;
};

export default TestImageData;
